/// <reference types="node" />

import { Server, Client, Socket } from 'libtcp';
import { FSServer, FSClient, Fileinfo } from '../';
import path = require('path');

let server = new Server();
let client = new Client();
let fsserver: FSServer = null;
let fsclient: FSClient = null;

async function createConnection() {
	await server.listen("localhost", 4567);
	await client.connect("localhost", 4567);
}

function setupServer() {
	fsserver = new FSServer(server);
	fsserver.setOnFileRequest((socket: Socket, message: any) => {
		return new Promise((resolve, reject) => {
			console.log('message : ' + message);
			resolve(path.join(__dirname, '..', 'gulpfile.js'));
		});
	});
}

function setupClient() {
	fsclient = new FSClient(client);
}

function sleep(ms: number) {
	return new Promise((resolve, reject) => {
		setTimeout(resolve, ms);
	});
}

async function test() {
	await createConnection();
	setupServer();
	setupClient();
	await sleep(100);
	let info = await fsclient.requestFile('file');
	console.log(info);
	console.log(info.content.length);
	console.log(info.content.toString('utf-8'));
	await sleep(100);
}

async function run() {
	try {
		await test();
	} catch (e) {
		console.log('Test Fail');
		process.exit(1);
	}
	console.log('Test OK');
	process.exit(0);
}

run();